<template>
   <div class="book-add"> 
    <el-form :model="formData" label-width="100px"  status-icon>
      <el-form-item label="图书名称：" prop="title">
        <el-input v-model="formData.title" placeholder="请输入图书名称"></el-input>
      </el-form-item>
      <el-form-item label="图书简介：" prop="description">
        <el-input v-model="formData.description" type="textarea" placeholder="请输入图书简介"></el-input>
      </el-form-item>
      <el-form-item label="价格：" prop="price">
        <el-input v-model="formData.price" placeholder="请输入价格"></el-input>
      </el-form-item>
      <el-form-item label="作者：" prop="author">
        <el-input v-model="formData.author" placeholder="请输入作者名字"></el-input>
      </el-form-item>
      <el-form-item label="出版社：" prop="publisher">
        <el-input v-model="formData.publisher" placeholder="请输入出版社"></el-input>
      </el-form-item>
      <el-form-item label="ISBN号：" prop="isbn">
        <el-input v-model="formData.isbn" placeholder="请输入ISBN号（978或979开头的13位数字）"></el-input>
      </el-form-item>
      <el-form-item label="库存：" prop="stock">
        <el-input v-model="formData.stock" placeholder="请输入库存"></el-input>
      </el-form-item>
      <el-form-item label="选择分类：" prop="categoryId">
  <el-select v-model="formData.categoryId" placeholder="请选择分类">
    <el-option
      v-for="item in categoryOptions"
      :key="item.value"
      :label="item.label"
      :value="item.value"
    />
  </el-select>
</el-form-item>
      <el-form-item label="是否上架：" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio :value="1">上架</el-radio>
          <el-radio :value="0">下架</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="是否推荐：" prop="isRecommended">
  <el-radio-group v-model="formData.isRecommended">
    <el-radio :value="1">不推荐</el-radio>
    <el-radio :value="2">推荐</el-radio>
  </el-radio-group>
</el-form-item>

<el-form-item label="是否轮播：" prop="isBanner">
  <el-radio-group v-model="formData.isBanner">
    <el-radio :value="1">不轮播</el-radio>
    <el-radio :value="2">轮播</el-radio>
  </el-radio-group>
</el-form-item>
      <el-form-item label="图书图片：" prop="coverUrl">
        <el-upload
          class="avatar-uploader"
          :http-request="customUpload"
          :show-file-list="false"
          :before-upload="beforeAvatarUpload"
          >
          <img v-if="formData.coverUrl" :src="formData.coverUrl" class="avatar" >
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
        <div style="margin-left: 20px; font-size: 14px; color: #666;">
      支持格式：JPG、PNG、GIF、WEBP<br/>
      大小不超过：2MB
    </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div> 
</template>

<script lang="ts" setup>
import { ref,onMounted,defineExpose } from 'vue';
import { ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import type { UploadProps } from 'element-plus'
import axios from 'axios'
axios.defaults.baseURL = "http://localhost:8080"
const uploadRef = ref(); 
// 分类列表
const categoryOptions = ref([])
const formData = ref({
  title: '',
  description: '',
  price: '',
  author: '',
  isbn: '',
  publisher: '',
  categoryId: '',
  status: 1,
  coverUrl: '',
  stock:'',
  isRecommended:1,
  isBanner:1
});
//修改图片上传
const customUpload: UploadProps['httpRequest'] = async (options) => {
  const { file } = options;

  try {
    const uploadFormData = new FormData(); 
    uploadFormData.append('file', file);

    const token = sessionStorage.getItem('token');
    const res = await axios.post('/upload', uploadFormData, {
      headers: {
        'Content-Type': 'multipart/form-data',
        Authorization: `${token}`
      }
    });

    if (res.data.code === 0) {
      formData.value.coverUrl = res.data.data;
    } else {
      ElMessage.error('上传失败');
    }
  } catch (error) {
    console.error('上传错误:', error);
    ElMessage.error('网络错误，请稍后再试');
  }
};
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  const validTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp']
  if (!validTypes.includes(rawFile.type)) {
    ElMessage.error('上传头像图片只能是 JPG/PNG/GIF/WebP 格式!')
    return false
  }
  if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('上传头像图片大小不能超过 2MB!')
    return false
  }
  return true
};

  //添加图书
const submitForm = async() => {
  
  const data = formData.value;
  const price = Number(data.price);
  const stock = Number(data.stock);
  const priceStr = formData.value.price.trim();
  //const stockStr = formData.value.stock.trim();
  if (!data.title.trim()) {
    ElMessage.warning('图书名称不能为空');
    return;
  }

  if (data.title.length < 2 || data.title.length > 100) {
    ElMessage.warning('图书名称长度应在 2 到 100 个字符之间');
    return;
  }

  if (!priceStr) {
  ElMessage.warning('价格不能为空');
  return;
}
 if (!/^\d+(\.\d{2})$/.test(priceStr)) {
  ElMessage.warning('请输入合法的两位小数格式（例如：10.00 或 5.20）');
  return;
}

  if (!data.author.trim()) {
    ElMessage.warning('作者不能为空');
    return;
  }

  if (!data.publisher.trim()) {
    ElMessage.warning('出版社不能为空');
    return;
  }

  if (!data.isbn.trim()) {
    ElMessage.warning('ISBN号不能为空');
    return;
  }

   if (!/^(978|979)\d{10}$/.test(data.isbn)) {
     ElMessage.warning('请输入合法的 ISBN 号（978或979开头的13位数字）');
     return;
   }

    if (!data.stock.trim()) {
   ElMessage.warning('库存不能为空');
   return;
 }
   if (!Number.isInteger(stock) || stock < 0) {
   ElMessage.warning('库存必须为非负整数');
   return;
   }

  if (!data.categoryId) {
    ElMessage.warning('请选择一个分类');
    return;
  }
    if (!formData.value.coverUrl) {
     ElMessage.warning('请上传图书封面图片');
     return;
   }

  try {
    const token = sessionStorage.getItem('token');
    const res = await axios.post('/admin/books/add',formData.value,{
    headers: {
      Authorization: `${token}`
    }});

    if (res.data.code === 0) {
      ElMessage.success('图书添加成功');
      resetForm(); // 提交成功后重置表单
    } else {
      ElMessage.error('提交失败: ISBN号已存在');
    }
   
  } catch (error) {
    console.error('请求失败:', error);
    ElMessage.error('网络错误，请稍后再试');
  }
};

//获取分类
const getCategoryList = async () => {
  try {
    const token = sessionStorage.getItem('token');
    const res = await axios.get('/categorys/list', 
     {
    headers: {
      Authorization: `${token}` // 添加 Token 到请求头 
    }}
  )
    if (res.data.code === 0) {
      console.log('原始分类数据:', res.data.data)
      categoryOptions.value = res.data.data.map(cat => ({
        value: cat.categoryId, 
        label: cat.categoryName
      }))
      console.log('映射后的分类:', categoryOptions.value)
    } else {
      ElMessage.error('获取分类失败')
    }
  } catch (err) {
    ElMessage.error('加载分类失败')
    console.error(err)
  }
}
const resetForm = () => {
  formData.value = {
    title: '',
    publisher: '',
    description: '',
    price: '',
    author: '',
    isbn: '',
    categoryId: '',
    status: 1,
    coverUrl: '',
    stock:'',
    isRecommended:1,
    isBanner:1
  };
};

onMounted(() => {
  getCategoryList()
})
</script>

<style scoped>
.book-add {
  width: 600px;
  margin: 0 0;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.upload-tip {
  font-size: 12px;
  color: #888;
  margin-top: 8px;
}
</style>